package com.wutuo.util;

import java.util.Collections;
import java.util.List;

/**
 * 分页工具类. <br>
 * <p/>
 * 2015年6月24日 下午4:56:51
 * <p/>
 * Company: 网龙公司
 * <p/>
 *
 * @author sujinwei
 * @version 1.0.0
 */
public class PageUtil {

    /**
     * 根据Web前端传来的分页信息和后台查询所得到的总记录条数 构造返回给Web前端的查询结果的分页信息。
     *
     * @param currentIndex
     * @param pageSize
     * @param totalCount
     * @return
     */
    public static TablePage getTablePage(int currentIndex, int pageSize, int totalCount) {
        int totalPage = getTotalPageByTotalNum(pageSize, totalCount);
        return new TablePage(currentIndex, pageSize, totalPage, totalCount);
    }

    public static int getTotalPageByTotalNum(int pageSize, int totalCount) {
        int totalPage = 0;
        if (totalCount == 0) {
            return totalPage;
        }
        if ((totalCount % pageSize) == 0) {
            totalPage = totalCount / pageSize;
        } else {
            totalPage = totalCount / pageSize + 1;
        }
        return totalPage;
    }

    public static int getCurrentPageFromIndex(int currentIndex, int pageSize, int totalRecords) {
        int fromIndex = (currentIndex - 1) * pageSize;
        return totalRecords > fromIndex ? fromIndex : totalRecords;
    }

    public static int getCurrentPageToIndex(int currentIndex, int pageSize, int totalRecords) {
        int toIndex = currentIndex * pageSize;
        return totalRecords > toIndex ? toIndex : totalRecords;
    }

    public static <T> List<T> getSubPage(List<T> list, int page, int pageCount) {
        int fromIndex = (page - 1) * pageCount;
        if (null == list || list.size() < fromIndex) {
            return Collections.emptyList();
        }
        int toIndex = fromIndex + pageCount;
        if (toIndex >= list.size()) {
            return list.subList(fromIndex, list.size());
        } else {
            return list.subList(fromIndex, toIndex);
        }
    }
}
